package com.lz.specification.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * TODO..
 *
 * @author: li
 * @date: 2019/1/14
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        Work thread1 = new Work("first", countDownLatch);
        Work thread2 = new Work("2nd", countDownLatch);
        Work thread3 = new Work("3th", countDownLatch);
        new Thread(thread1).start();
        new Thread(thread2).start();
        new Thread(thread3).start();


        countDownLatch.await(10, TimeUnit.SECONDS);
        System.out.println("over");
    }
}

class Work implements Runnable {
    private String content;
    private final CountDownLatch countDownLatch;

    Work(String content, CountDownLatch countDownLatch) {
        this.content = content;
        this.countDownLatch = countDownLatch;
    }

    @Override

    public void run() {
        if (Math.random() < 0.5) {
            throw new RuntimeException("模拟发生异常");
        }
        countDownLatch.countDown();

        System.out.println("完毕");
    }


}
